<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>加速</title>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<script src="./ball.js"></script>
<script>
  window.onload = function () {
    var oCanvas = document.querySelector("#canvas"),
      oGc = oCanvas.getContext('2d'),
      width = oCanvas.width, height = oCanvas.height,
      ball = new Ball(width / 2, height / 2);
    ball.fill( oGc );
    var animation = null;
    var directionArry = [];
    var dir = {
      37: 'top',
      38: 'left',
      39: 'bottom',
      40: 'right'
    }

    document.addEventListener("keydown", function aaa(ev) {
      var oEvent = ev || event;
      keyCode = oEvent.keyCode;
      if(dir[keyCode]) {
        keyCodeArry = addKeyCodeArry(dir[keyCode], directionArry);
        createMove()
      }

    }, false);
    document.addEventListener("keyup", function (ev) {
      var oEvent = ev || event;
      keyCode = oEvent.keyCode;
      if(dir[keyCode]) {
        keyCodeArry = deletKeyCodeArry(dir[keyCode], directionArry);
        cancelAnimationFrame(animation)
      }
    }, false);


    function addKeyCodeArry(num, arr) {
      var check = 0;
      for(var i = 0; i < arr.length; i++) {
        if(arr[i] == num) {
          check = 1;
        }
      }
      if(check == 0) {
        arr.push(num);
      }
      return arr;
    }

    function deletKeyCodeArry(num, arr) {
      for(var i = 0; i < arr.length; i++) {
        if(arr[i] == num) {
          arr.splice(i, 1);
        }
      }
      return arr;
    }


    function createMove(ev) {
      var move = {
        top: (speed) => ball.x -= speed,
        left: (speed) => ball.y -= speed,
        bottom: (speed) => ball.x += speed,
        right: (speed) => ball.y += speed
      }


      if(directionArry.length > 0) {
        oGc.clearRect(0, 0, width, height);
        for(var i=0; i < directionArry.length; i++) {
          direction = directionArry[i];
          move[direction](5)
          checkBorder();
        }
        ball.fill(oGc);
      }
      animation = requestAnimationFrame(createMove)
    }

    // 判断边界
    function checkBorder() {
      //碰到左边界
      if ( ball.x < ball.radius ) {
        ball.x = ball.radius;
      }
      //碰到上边界
      else if ( ball.y < ball.radius ) {
        ball.y = ball.radius;
      }
      //碰到右边界
      else if ( ball.x > width - ball.radius ) {
        ball.x = width - ball.radius;
      }
      //碰到下边界
      else if ( ball.y > height - ball.radius ){
        ball.y = height - ball.radius;
      }
    }
  }
</script>
</body>
</html>
